package cn.ztydata.teachingsystem.heaven.dao;

import cn.ztydata.teachingsystem.heaven.cons.MsgTemplate;
import cn.ztydata.teachingsystem.heaven.entity.Chapter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 章节Dao类
 * Created by chenxin on 2014/12/15.
 */
@Repository
public class ChapterDao extends BaseDao {
    /**
     * 保存章节
     * @param chapter 章节实体类
     * @return boolean
     *
     * @author cx
     * @since 2014-12-15
     */
    public boolean save(Chapter chapter) {
        String sql = "INSERT INTO t_chapter(sName,iParentId,iCourseId) VALUES(:name,:parentId,:courseId)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        SqlParameterSource sps = new MapSqlParameterSource().addValue("name", chapter.getName())
                .addValue("parentId", chapter.getParentId())
                .addValue("courseId", chapter.getCourseId());

        int result = namedParameterJdbcTemplate.update(sql, sps, keyHolder);
        if (result == 1) {
            log.debug("result == 1");
            chapter.setId(keyHolder.getKey().longValue());
            return true;
        }

        log.debug("result != 1");
        return false;
    }

    /**
     * 查询章节的模块信息
     * @param nodeId 节点ID
     * @return Chapter
     *
     * @author cx
     * @since 2014-12-16
     */
    public Chapter getForModule(final long nodeId) {
        String sql = "SELECT iPeriod,tiTeachingMethod,iTeachingWeek FROM t_chapter WHERE id=:nodeId";

        try {
            log.debug("正常返回查询章节的模块信息");
            return namedParameterJdbcTemplate.queryForObject(sql, new MapSqlParameterSource().addValue("nodeId", nodeId), new RowMapper<Chapter>() {
                @Override
                public Chapter mapRow(ResultSet rs, int rowNum) throws SQLException {
                    Chapter entity = new Chapter();

                    entity.setPeriod(rs.getInt("iPeriod"));
                    entity.setTeachingMethod(rs.getInt("tiTeachingMethod"));
                    entity.setTeachingWeek(rs.getInt("iTeachingWeek"));

                    return entity;
                }
            });
        } catch (EmptyResultDataAccessException ex) {
            log.debug("根据节点ID查询章节的模块信息失败");
            log.warn(MessageFormat.format(MsgTemplate.RECORD_NOT_FOUND, "nodeId", nodeId));
            return null;
        }
    }

    /**
     * 更新模块信息
     * @param chapter 章节实体类
     * @return boolean
     *
     * @author cx
     * @since 2014-12-16
     */
    public boolean updateForModule(Chapter chapter) {
        String sql = "UPDATE t_chapter SET iPeriod=:period,tiTeachingMethod=:teachingMethod,iTeachingWeek=:teachingWeek WHERE id=:nodeId";
        SqlParameterSource sps = new MapSqlParameterSource().addValue("period", chapter.getPeriod())
                .addValue("teachingMethod", chapter.getTeachingMethod())
                .addValue("teachingWeek", chapter.getTeachingWeek())
                .addValue("nodeId", chapter.getId());

        log.debug("更新模块信息");
        return namedParameterJdbcTemplate.update(sql, sps) == 1;
    }

    /**
     * 更新节点名称
     *
     * @author chenxin
     * @since 2014/12/19
     */
    public boolean updateName(Chapter chapter) {
        String sql = "UPDATE t_chapter SET sName=:name WHERE id=:id AND iParentId > 0";
        SqlParameterSource sps = new MapSqlParameterSource().addValue("name", chapter.getName())
                .addValue("id", chapter.getId());

        log.debug("更新节点名称");
        return namedParameterJdbcTemplate.update(sql, sps) == 1;
    }

    public boolean updateRootName(final String name, final long courseId) {
        String sql = "UPDATE t_chapter SET sName=:name WHERE iCourseId=:courseId AND iParentId = 0";
        SqlParameterSource sps = new MapSqlParameterSource().addValue("name", name)
                .addValue("courseId", courseId);

        return namedParameterJdbcTemplate.update(sql, sps) == 1;
    }

    /**
     * 获取父节点ID
     *
     * @author chenxin
     * @since 2014/12/19
     */
    public Long getParentId(final long nodeId) {
        String sql = "SELECT iParentId FROM t_chapter WHERE id=:nodeId";

        try {
            log.debug("获取父节点ID");
            return namedParameterJdbcTemplate.queryForObject(sql, new MapSqlParameterSource().addValue("nodeId", nodeId), Long.class);
        } catch (EmptyResultDataAccessException ex) {
            log.debug("获取父节点ID失败");
            log.warn(MessageFormat.format(MsgTemplate.RECORD_NOT_FOUND, "nodeId", nodeId));
            return null;
        }
    }

    /**
     * 更新节点的父节点
     *
     * @author chenxin
     * @since 2014/12/23
     */
    public boolean updateParentId(final long nodeId, final long parentId) {
        String sql = "UPDATE t_chapter SET iParentId=:parentId WHERE id=:nodeId";

        log.debug("更新节点的父节点");
        return namedParameterJdbcTemplate.update(sql, new MapSqlParameterSource().addValue("parentId", parentId).addValue("nodeId", nodeId)) == 1;
    }

    /**
     * 删除节点
     *
     * @author chenxin
     * @since 2014/12/19
     */
    public boolean deleteById(final long nodeId) {
        String sql = "DELETE FROM t_chapter WHERE id=:nodeId";

        log.debug("删除节点");
        return namedParameterJdbcTemplate.update(sql, new MapSqlParameterSource().addValue("nodeId", nodeId)) == 1;
    }

    /**
     * 批量获取子节点信息
     *
     * @author chenxin
     * @since 2014/12/22
     */
    public List<Chapter> getAll(final List<Long> sonIds) {
        if (sonIds == null || sonIds.isEmpty()) {
            log.debug("如果sonIds不为空：sonIds == null || sonIds.isEmpty()");
            return Lists.newArrayList();
        }

        String sql = "SELECT id,sName FROM t_chapter WHERE id IN (:sonIds)";
        SqlParameterSource sps = new MapSqlParameterSource().addValue("sonIds", sonIds);

        log.debug("批量获取子节点信息");
        return namedParameterJdbcTemplate.query(sql, sps, new RowMapper<Chapter>() {
            @Override
            public Chapter mapRow(ResultSet rs, int rowNum) throws SQLException {
                Chapter entity = new Chapter();

                entity.setId(rs.getLong("id"));
                entity.setName(rs.getString("sName"));

                return entity;
            }
        });
    }

    /**
     * 获取章节根节点
     *
     * @author chenxin
     * @since 2014/12/22
     */
    public Chapter getRootNode(final long courseId) {
        String sql = "SELECT id,sName FROM t_chapter WHERE iParentId=0 AND iCourseId=:courseId";
        SqlParameterSource sps = new MapSqlParameterSource().addValue("courseId", courseId);

        try {
            log.debug("获取章节根节点");
            return namedParameterJdbcTemplate.queryForObject(sql, sps, new RowMapper<Chapter>() {
                @Override
                public Chapter mapRow(ResultSet rs, int rowNum) throws SQLException {
                    Chapter entity = new Chapter();

                    entity.setId(rs.getLong("id"));
                    entity.setName(rs.getString("sName"));

                    log.debug("返回实体entity");
                    return entity;
                }
            });
        } catch (EmptyResultDataAccessException ex) {
            log.debug("获取章节根节点失败");
            log.warn(MessageFormat.format(MsgTemplate.RECORD_NOT_FOUND, "courseId", courseId));
            return null;
        }
    }

    /**
     * 获取节点所属课程ID
     *
     * @author chenxin
     * @since 2014/12/30
     */
    public Long getCourseId(final long nodeId) {
        String sql = "SELECT iCourseId FROM t_chapter WHERE id=:nodeId";

        try {
            log.debug("获取节点所属课程ID");
            return namedParameterJdbcTemplate.queryForObject(sql, new MapSqlParameterSource().addValue("nodeId", nodeId), Long.class);
        } catch (EmptyResultDataAccessException ex) {
            log.debug("获取节点所属课程ID失败");
            log.warn(MessageFormat.format(MsgTemplate.RECORD_NOT_FOUND, "nodeId", nodeId));
            return null;
        }
    }

    /**
     * 查询章节节点的名称
     * @param chapterIds 章节ID集合
     * @return Map
     *
     * @author cx
     * @since 215/03/19
     */
    public Map<Long, String> getNames(final Set<Long> chapterIds) {
        final Map<Long, String> result = Maps.newHashMap();

        String sql = "SELECT id,sName FROM t_chapter WHERE id IN (:chapterIds)";

        namedParameterJdbcTemplate.query(sql, new MapSqlParameterSource().addValue("chapterIds", chapterIds), new RowMapper<Object>() {
            @Override
            public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
                result.put(rs.getLong("id"), rs.getString("sName"));

                return null;
            }
        });

        log.debug("return 章节名称");
        return result;
    }

    /**
     * 根据父节点编号获取所有子节点
     * @param parentId 父节点编号
     * @return List
     *
     * @author fanruiping
     * @since 2015-04-03
     */
    public List<Chapter> getByParentId(Long parentId){
        String sql = "SELECT id,sName FROM t_chapter WHERE iParentId=:parentId";

        return namedParameterJdbcTemplate.query(sql, new MapSqlParameterSource().addValue("parentId", parentId), new RowMapper<Chapter>() {
            @Override
            public Chapter mapRow(ResultSet rs, int i) throws SQLException {
                Chapter chapter = new Chapter();

                chapter.setId(rs.getLong("id"));
                chapter.setName(rs.getString("sName"));

                return chapter;
            }
        });
    }
}
